<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>Authentication - Security - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w947" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w947-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w947-collapse" class="collapse navbar-collapse"><ul id="w948" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w949" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-931" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-931" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-932" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-932" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item" href="#navigation-933" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-933" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-934" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-934" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-935" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-935" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item" href="#navigation-936" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-936" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-937" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-937" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item" href="#navigation-938" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-938" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item active" href="#navigation-939" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-939" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item active" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item" href="#navigation-940" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-940" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-941" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-941" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-942" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-942" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-943" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-943" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-944" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-944" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-945" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-945" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item" href="#navigation-946" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-946" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>Authentication <span id="authentication"></span><a href="#authentication" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#configuring-user">Configuring yii\web\User</a></li>
<li><a href="#implementing-identity">Implementing yii\web\IdentityInterface</a></li>
<li><a href="#using-user">Using yii\web\User</a></li>
<li><a href="#auth-events">Authentication Events</a></li></ol></div>
<p>Authentication is the process of verifying the identity of a user. It usually uses an identifier 
(e.g. a username or an email address) and a secret token (e.g. a password or an access token) to judge 
if the user is the one whom he claims as. Authentication is the basis of the login feature.</p>
<p>Yii provides an authentication framework which wires up various components to support login. To use this framework, 
you mainly need to do the following work:</p>
<ul>
<li>Configure the <a href="./yii-web-user.html">user</a> application component;</li>
<li>Create a class that implements the <a href="./yii-web-identityinterface.html">yii\web\IdentityInterface</a> interface.</li>
</ul>
<h2>Configuring <a href="./yii-web-user.html">yii\web\User</a>  <span id="configuring-user"></span><a href="#configuring-user" class="hashlink">&para;</a></h2><p>The <a href="./yii-web-user.html">user</a> application component manages the user authentication status. It requires you to 
specify an <a href="./yii-web-user.html#$identityClass-detail">identity class</a> which contains the actual authentication logic.
In the following application configuration, the <a href="./yii-web-user.html#$identityClass-detail">identity class</a> for
<a href="./yii-web-user.html">user</a> is configured to be <code>app\models\User</code> whose implementation is explained in 
the next subsection:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">return</span> [
    <span class="hljs-string">'components'</span> =&gt; [
        <span class="hljs-string">'user'</span> =&gt; [
            <span class="hljs-string">'identityClass'</span> =&gt; <span class="hljs-string">'app\models\User'</span>,
        ],
    ],
];
</code></pre>
<h2>Implementing <a href="./yii-web-identityinterface.html">yii\web\IdentityInterface</a>  <span id="implementing-identity"></span><a href="#implementing-identity" class="hashlink">&para;</a></h2><p>The <a href="./yii-web-user.html#$identityClass-detail">identity class</a> must implement the <a href="./yii-web-identityinterface.html">yii\web\IdentityInterface</a> which contains
the following methods:</p>
<ul>
<li><a href="./yii-web-identityinterface.html#findIdentity()-detail">findIdentity()</a>: it looks for an instance of the identity
class using the specified user ID. This method is used when you need to maintain the login status via session.</li>
<li><a href="./yii-web-identityinterface.html#findIdentityByAccessToken()-detail">findIdentityByAccessToken()</a>: it looks for
an instance of the identity class using the specified access token. This method is used when you need
to authenticate a user by a single secret token (e.g. in a stateless RESTful application).</li>
<li><a href="./yii-web-identityinterface.html#getId()-detail">getId()</a>: it returns the ID of the user represented by this identity instance.</li>
<li><a href="./yii-web-identityinterface.html#getAuthKey()-detail">getAuthKey()</a>: it returns a key used to verify cookie-based login.
The key is stored in the login cookie and will be later compared with the server-side version to make
sure the login cookie is valid.</li>
<li><a href="./yii-web-identityinterface.html#validateAuthKey()-detail">validateAuthKey()</a>: it implements the logic for verifying
the cookie-based login key.</li>
</ul>
<p>If a particular method is not needed, you may implement it with an empty body. For example, if your application 
is a pure stateless RESTful application, you would only need to implement <a href="./yii-web-identityinterface.html#findIdentityByAccessToken()-detail">findIdentityByAccessToken()</a>
and <a href="./yii-web-identityinterface.html#getId()-detail">getId()</a> while leaving all other methods with an empty body.</p>
<p>In the following example, an <a href="./yii-web-user.html#$identityClass-detail">identity class</a> is implemented as 
an <a href="guide-db-active-record.html">Active Record</a> class associated with the <code>user</code> database table.</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">ActiveRecord</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">web</span>\<span class="hljs-title">IdentityInterface</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ActiveRecord</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IdentityInterface</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tableName</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'user'</span>;
    }

    <span class="hljs-comment">/**
     * Finds an identity by the given ID.
     *
     * <span class="hljs-doctag">@param</span> string|integer $id the ID to be looked for
     * <span class="hljs-doctag">@return</span> IdentityInterface|null the identity object that matches the given ID.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findIdentity</span><span class="hljs-params">(<span class="hljs-variable">$id</span>)</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">static</span>::findOne(<span class="hljs-variable">$id</span>);
    }

    <span class="hljs-comment">/**
     * Finds an identity by the given token.
     *
     * <span class="hljs-doctag">@param</span> string $token the token to be looked for
     * <span class="hljs-doctag">@return</span> IdentityInterface|null the identity object that matches the given token.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findIdentityByAccessToken</span><span class="hljs-params">(<span class="hljs-variable">$token</span>, <span class="hljs-variable">$type</span> = null)</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">static</span>::findOne([<span class="hljs-string">'access_token'</span> =&gt; <span class="hljs-variable">$token</span>]);
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@return</span> int|string current user ID
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getId</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;id;
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@return</span> string current user auth key
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAuthKey</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;auth_key;
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@param</span> string $authKey
     * <span class="hljs-doctag">@return</span> boolean if auth key is valid for current user
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateAuthKey</span><span class="hljs-params">(<span class="hljs-variable">$authKey</span>)</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;getAuthKey() === <span class="hljs-variable">$authKey</span>;
    }
}
</code></pre>
<p>As explained previously, you only need to implement <code>getAuthKey()</code> and <code>validateAuthKey()</code> if your application
uses cookie-based login feature. In this case, you may use the following code to generate an auth key for each
user and store it in the <code>user</code> table:</p>
<pre><code class="hljs php language-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ActiveRecord</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IdentityInterface</span>
</span>{
    ......
    
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">beforeSave</span><span class="hljs-params">(<span class="hljs-variable">$insert</span>)</span>
    </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">parent</span>::beforeSave(<span class="hljs-variable">$insert</span>)) {
            <span class="hljs-keyword">if</span> (<span class="hljs-variable">$this</span>-&gt;isNewRecord) {
                <span class="hljs-variable">$this</span>-&gt;auth_key = \Yii::<span class="hljs-variable">$app</span>-&gt;security-&gt;generateRandomString();
            }
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }
}
</code></pre>
<blockquote class="note"><p><strong>Note: </strong>Do not confuse the <code>User</code> identity class with <a href="./yii-web-user.html">yii\web\User</a>. The former is the class implementing
  the authentication logic. It is often implemented as an <a href="guide-db-active-record.html">Active Record</a> class associated
  with some persistent storage for storing the user credential information. The latter is an application component
  class responsible for managing the user authentication state.</p>
</blockquote>
<h2>Using <a href="./yii-web-user.html">yii\web\User</a>  <span id="using-user"></span><a href="#using-user" class="hashlink">&para;</a></h2><p>You mainly use <a href="./yii-web-user.html">yii\web\User</a> in terms of the <code>user</code> application component. </p>
<p>You can detect the identity of the current user using the expression <code>Yii::$app-&gt;user-&gt;identity</code>. It returns
an instance of the <a href="./yii-web-user.html#$identityClass-detail">identity class</a> representing the currently logged-in user,
or null if the current user is not authenticated (meaning a guest). The following code shows how to retrieve
other authentication-related information from <a href="./yii-web-user.html">yii\web\User</a>:</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// the current user identity. Null if the user is not authenticated.</span>
<span class="hljs-variable">$identity</span> = Yii::<span class="hljs-variable">$app</span>-&gt;user-&gt;identity;

<span class="hljs-comment">// the ID of the current user. Null if the user not authenticated.</span>
<span class="hljs-variable">$id</span> = Yii::<span class="hljs-variable">$app</span>-&gt;user-&gt;id;

<span class="hljs-comment">// whether the current user is a guest (not authenticated)</span>
<span class="hljs-variable">$isGuest</span> = Yii::<span class="hljs-variable">$app</span>-&gt;user-&gt;isGuest;
</code></pre>
<p>To login a user, you may use the following code:</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// find a user identity with the specified username.</span>
<span class="hljs-comment">// note that you may want to check the password if needed</span>
<span class="hljs-variable">$identity</span> = User::findOne([<span class="hljs-string">'username'</span> =&gt; <span class="hljs-variable">$username</span>]);

<span class="hljs-comment">// logs in the user </span>
Yii::<span class="hljs-variable">$app</span>-&gt;user-&gt;login(<span class="hljs-variable">$identity</span>);
</code></pre>
<p>The <a href="./yii-web-user.html#login()-detail">yii\web\User::login()</a> method sets the identity of the current user to the <a href="./yii-web-user.html">yii\web\User</a>. If session is 
<a href="./yii-web-user.html#$enableSession-detail">enabled</a>, it will keep the identity in the session so that the user
authentication status is maintained throughout the whole session. If cookie-based login (i.e. "remember me" login)
is <a href="./yii-web-user.html#$enableAutoLogin-detail">enabled</a>, it will also save the identity in a cookie so that
the user authentication status can be recovered from the cookie as long as the cookie remains valid.</p>
<p>In order to enable cookie-based login, you need to configure <a href="./yii-web-user.html#$enableAutoLogin-detail">yii\web\User::$enableAutoLogin</a> to be
true in the application configuration. You also need to provide a duration time parameter when calling 
the <a href="./yii-web-user.html#login()-detail">yii\web\User::login()</a> method. </p>
<p>To logout a user, simply call</p>
<pre><code class="hljs php language-php">Yii::<span class="hljs-variable">$app</span>-&gt;user-&gt;logout();
</code></pre>
<p>Note that logging out a user is only meaningful when session is enabled. The method will clean up
the user authentication status from both memory and session. And by default, it will also destroy <em>all</em>
user session data. If you want to keep the session data, you should call <code>Yii::$app-&gt;user-&gt;logout(false)</code>, instead.</p>
<h2>Authentication Events  <span id="auth-events"></span><a href="#auth-events" class="hashlink">&para;</a></h2><p>The <a href="./yii-web-user.html">yii\web\User</a> class raises a few events during the login and logout processes. </p>
<ul>
<li><a href="./yii-web-user.html#EVENT_BEFORE_LOGIN-detail">EVENT_BEFORE_LOGIN</a>: raised at the beginning of <a href="./yii-web-user.html#login()-detail">yii\web\User::login()</a>.
If the event handler sets the <a href="./yii-web-userevent.html#$isValid-detail">isValid</a> property of the event object to be false,
the login process will be cancelled. </li>
<li><a href="./yii-web-user.html#EVENT_AFTER_LOGIN-detail">EVENT_AFTER_LOGIN</a>: raised after a successful login.</li>
<li><a href="./yii-web-user.html#EVENT_BEFORE_LOGOUT-detail">EVENT_BEFORE_LOGOUT</a>: raised at the beginning of <a href="./yii-web-user.html#logout()-detail">yii\web\User::logout()</a>.
If the event handler sets the <a href="./yii-web-userevent.html#$isValid-detail">isValid</a> property of the event object to be false,
the logout process will be cancelled. </li>
<li><a href="./yii-web-user.html#EVENT_AFTER_LOGOUT-detail">EVENT_AFTER_LOGOUT</a>: raised after a successful logout.</li>
</ul>
<p>You may respond to these events to implement features such as login audit, online user statistics. For example,
in the handler for <a href="./yii-web-user.html#EVENT_AFTER_LOGIN-detail">EVENT_AFTER_LOGIN</a>, you may record the login time and IP
address in the <code>user</code> table.</p>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:29 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
